package org.hsieh.tr.explore.dbconn;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import org.hsieh.tr.explore.dbsource.IDatabaseInfo;
import org.hsieh.tr.explore.exception.ExceptionHandler;

public abstract class ConnectionFactory {

    public static Connection connect(IDatabaseInfo info) throws Exception {
	if (info == null) {
	    throw new IllegalArgumentException("DB connect info");
	}
	JDBCClassLoader loader = null;
	if (info.getDriverClassPath() != null
		&& !info.getDriverClassPath().isEmpty()) {
	    // load by JDBCClassLoader
	    URL[] urls = new URL[info.getDriverClassPath().size()];
	    for (int i = 0, n = info.getDriverClassPath().size(); i < n; i++) {
		String str = info.getDriverClassPath().get(i);
		try {

		    urls[i] = new File(str).toURI().toURL();
		} catch (MalformedURLException e) {
		    ExceptionHandler.handle(e);
		}
	    }

	    loader = new JDBCClassLoader(urls);
	} else
	    loader = new JDBCClassLoader();

	Driver loadClass = (Driver) loader.loadClass(info.getDriverClassName())
		.newInstance();
	Properties props = new Properties();
	props.setProperty("user", info.getUserName());
	props.setProperty("password", info.getPassword());
	loadClass.connect(info.composeUrl(), props);
	Connection connection = loadClass.connect(info.composeUrl(), props);
	return connection;
    }
}
